<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-if="open" v-model="open" width="1200px" append-to-body>
    <div v-loading="loading">
      <el-form ref="form" :rules="rules" :model="form" label-width="95px" :inline="true" :disabled="disabledEdit">

        <el-form-item label="跟单方式:" prop="followTypeDictValue">
          <el-select v-model="form.followTypeDictValue" clearable reserve-keyword placeholder="请选择跟单方式">
            <el-option v-for="dict in follow_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前跟单人" prop="followUserId">
          <el-select v-model="form.followUserId" filterable clearable remote reserve-keyword placeholder="请选择当前跟单人"
            :loading="loading">
            <el-option v-for="item in userList" :key="item.value" :label="item.realityName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟单时间" prop="followDate">
          <el-date-picker v-model="form.followDate" style="width: 240px" value-format="YYYY-MM-DD hh:mm:ss" type="date"
            placeholder="选择跟单时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="跟单阶段:" prop="followStageId">
          <el-select v-model="form.followStageId" placeholder="请选择跟单阶段" clearable @change="hanldeFollowStageChange">
            <el-option v-for="item in followStage" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟单状态:">
          <el-select v-model="form.followStageId" placeholder="请选择跟单状态" clearable disabled>
            <el-option v-for="item in followStage" :key="item.id" :label="selectDictLabel(follow_stage, item.stageName)"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="supplierId">
          <el-select v-model="form.supplierId" filterable clearable remote reserve-keyword placeholder="请选择客户"
            :remote-method="(query) => remoteMethod(query, 'supplier', 'supplierName')" :loading="loading"
            :disabled="supplierDisabled" @change="customerChange">
            <el-option v-for="item in supplierOptions" :key="item.id" :label="item.supplierName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人:" prop="contacts">
          <el-select v-model="form.contacts" filterable clearable remote reserve-keyword placeh :loading="loading">
            <el-option v-for="item in contactsOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="延期天数:" prop="delayDays" v-show="followStatusDictValue === '2'" @change="">
          <el-input v-model="form.delayDays" @change="handleDelayChange(form)"></el-input>
        </el-form-item>
        <el-form-item label="延迟到期:" prop="delayDate" v-show="followStatusDictValue === '2'">
          <el-date-picker v-model="form.delayDate" style="width: 240px" value-format="YYYY-MM-DD hh:mm:ss" type="date"
            placeholder="选择日期" @change="handleDelayDateChange(form)" />
        </el-form-item>
        <el-form-item label="周期:" prop="periodicNum" v-show="followStatusDictValue === '3'">
          <el-input v-model="form.periodicNum" @change="handlePeriodicNumChange(form)"></el-input>
        </el-form-item>
        <el-form-item label="续费时间:" prop="beginDate" v-show="followStatusDictValue === '3'">
          <el-date-picker v-model="form.beginDate" style="width: 240px" value-format="YYYY-MM-DD hh:mm:ss" type="date"
            placeholder="选择日期" @change="handlePeriodicNumChange(form)" />
        </el-form-item>

        <el-form-item label="续费金额:" prop="payAmount">
          <el-input v-model="form.payAmount"></el-input>
        </el-form-item>
        <el-form-item label="到期日期:" prop="endDate">
          <el-date-picker v-model="form.endDate" style="width: 240px" value-format="YYYY-MM-DD hh:mm:ss" type="date"
            placeholder="选择日期" @change="handleEndDateChange(form)" />
        </el-form-item>
        <el-form-item label="断续原因:" prop="stopReasonDictValue" v-show="followStatusDictValue === '4'">
          <el-select v-model="form.stopReson" clearable reserve-keyword placeholder="请选择断续原因">
            <el-option v-for="item in stop_reson" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="转为缴费单" v-show="form.followStage ==3">
          <template #default="scope">
            <div>
              <el-radio-group v-model="form.translateToOrder">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
              <el-form-item label="日期" style="width:100%">
                <el-date-picker v-model="form.renewalTime" style="width: 240px" value-format="YYYY-MM-DD hh:mm:ss"
                  type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="缴费类型" style="padding-top:10px">
                <el-select>
                  <el-option v-for="item in stop_reson" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
          </template>
</el-form-item> -->
        <el-form-item label="申请原因:" prop="requestReason" v-show="followStatusDictValue === '2'">
          <el-input type="textarea" style="width: 1050px" :rows="4" v-model="form.requestReason"></el-input>
        </el-form-item>
        <el-form-item label="进展内容:" prop="comment">
          <el-input type="textarea" style="width: 1050px" :rows="4" v-model="form.comment"></el-input>
        </el-form-item>
        <!-- <el-card v-show="form.auditUserId">
          <el-form-item label="审核人:">
            <el-select></el-select>
          </el-form-item>
          <el-form-item label="审核状态:">
            <el-select></el-select>
          </el-form-item>
          <el-form-item label="审核批注:" prop="orderProgress">
            <el-input type="textarea" style="width: 1050px" :rows="4" v-model="form.orderProgress"></el-input>
          </el-form-item>
        </el-card> -->
      </el-form>

    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading" v-show="!disabledEdit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import modelMixin from '@/mixins/modelMixin'
import { listUser } from '@/api/system/user';
import { listFollowStage } from '@/api/goods/followStage';
import { getSupplier } from '@/api/goods/supplier'
import payOrderDetail from '@/api/goods/payOrderDetail'
import { addFollowOrder } from '@/api/goods/followOrder'
import { formatDate } from '@/utils/index'

export default {
  name: 'addForm',
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      title: '',
      funcObj: payOrderDetail,
      form: {},
      supplierOptions: [],//客户
      contactsOptions: [],//联系人    
      active: 1,
      baseInput: 200,
      data: [],
      dateRange: [],
      dataSource: [],
      loading: false,
      followStage: [],  //跟单阶段
      follow_type: [],//跟单方式
      stop_reson: [],//断续原因
      userList: [], //跟单人列表
      follow_stage: [],//跟单状态
      followStatusDictValue: '',
      disabledEdit: false,
      supplierDisabled: false,
      rules: {
        followTypeDictValue: [
          { required: true, message: "跟单方式不能为空", trigger: "blur" }
        ],
        followUserId: [
          { required: true, message: "跟单人不能为空", trigger: "blur" }
        ],
        followDate: [
          { required: true, message: "跟单时间不能为空", trigger: "blur" }
        ],
        followStageId: [
          { required: true, message: "跟单阶段不能为空", trigger: "blur" }
        ],
        contacts: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        payAmount: [
          { required: true, message: "续费金额不能为空", trigger: "blur" }
        ],
      },
    };
  },
  methods: {
    edit(row) {
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.open = true
      this.title = '续费进展'
      this.form = {}
      this.followStatusDictValue = ''
      this.dataSource = []
      this.getDicts(['follow_type', 'stop_reson', 'follow_stage']);
      this.getDetail(row)
      this.listSysUser()

      listFollowStage({typeCategory:0}).then(res => {
        this.followStage = res.rows.filter(item => item.display === "0")
      })
      this.supplierDisabled = true
    },
    view(row) {
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.form = {}
      this.followStatusDictValue = ''
      this.open = true
      this.disabledEdit = true
      this.title = '跟单详情'
      this.form = row
      this.getDicts(['follow_type', 'stop_reson', 'follow_stage']);
      this.listSysUser()
      listFollowStage({typeCategory:0}).then(res => {
        this.followStage = res.rows
        this.detailAfter()
      })
    },
    cancel() {
      this.open = false;
    },
    hanldeFollowStageChange(id) {
      var followStageData = this.followStage.find(function (obj) {
        return obj.id == id;
      })
      if (followStageData) {
        this.followStatusDictValue = followStageData.stageName
      }
    },
    handleSelectionChange(val) {
      this.multiple = val.length > 1;
    },
    selectHandle(row) {
      return 1;
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },

    remoteMethod(query, listKey, key) {
      const optionKey = listKey + 'Options';
      if (query !== '') {

        this[optionKey] = this[listKey + 'List'].filter(item => {
          return item[key].toLowerCase()
            .indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this[optionKey] = this[listKey + 'List'];
      }

    },
    customerChange(value) {
      getSupplier(value).then(res => {
        if (res.data.supplierContactList.length > 0) {
          this.contactsOptions = res.data.supplierContactList
        } else {
          this.form.contacts = ""
          this.contactsOptions = []
        }
      })
    },
    listSysUser() {
      listUser().then(res => {
        this.userList = res.rows
      }).catch(err => {
        console.log(err)
      });
    },
    classifyForm() {
      // this.form.followUserId = this.form.userId
      this.form.payOrderDetailId = this.form.id
      this.form.followStatusDictValue = this.followStatusDictValue
      delete this.form.id
    },
    detailAfter() {
      this.hanldeFollowStageChange(this.form.followStageId)
    },
    getDetail(row) {
      this.loading = true
      this.funcObj.get(row.id).then(res => {
        this.loading = false
        if (res.code == 200) {
          this.form = res.data || {};
          this.form.followUserId = this.form.userId
          this.form.followDate = formatDate(new Date())
          if (typeof (this.detailAfter) === 'function') {
            this.detailAfter()
          }
          this.customerChange(this.form.supplierId)
        } else {
          this.$modal.msgError(res.msg)
        }
      }).catch(err => {
        this.loading = false
        console.log('err :>> ', err);
      })
    },
    handleDelayChange(row) {
      let date = row.endDate
      date = Date.parse(new Date(date)) / 1000; // 转换成时间戳，返回值是ms，除1000后转化成秒
      date += (86400) * row.delayDays; // 一天是86400秒
      let newDate = new Date(parseInt(date) * 1000); // 把时间戳转换成日期
      //这步就是给所需变化的值赋值
      row.delayDate = formatDate(newDate)
    },
    handleDelayDateChange(row) {
      let date1 = Date.parse(new Date(row.endDate))
      let date2 = Date.parse(new Date(row.delayDate))
      row.delayDays = parseInt(Math.abs(date2 - date1) / 1000 / 86400)
    },
    //提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          typeof (this.classifyForm) === 'function' && this.classifyForm()
          this.loading = true
          addFollowOrder(this.form).then(res => {
            this.loading = false
            if (res.code == 200) {
              this.$modal.msgSuccess('新增成功')
              if (close) {
                this.open = false;
              }
              this.$emit('ok');
            } else {
              this.$modal.msgError(res.msg)
            }
          }).catch(err => {
            console.log('err :>> ', err);
            this.loading = false
          })
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>